package com.icesoft.core.web.configurer.filter;

import com.icesoft.core.web.helper.RequestHold;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@AllArgsConstructor
public class IpPathFilter implements Filter {

	private final String whiteIps;
	private final AdminServerIpHelper adminServerIpHelper;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String userIp = RequestHold.getRemoteIP((HttpServletRequest) request);
		if (RequestHold.isLocalhost(userIp) || (whiteIps != null && whiteIps.contains(userIp))) {
			chain.doFilter(request, response);
		} else if (adminServerIpHelper != null) {
			for (String whiteIps : adminServerIpHelper.getAdminServerIps()) {
				if (whiteIps.contains(userIp)) {
					chain.doFilter(request, response);
				}
			}
		} else {
			log.warn("not white ip , userIp={}", userIp);
			HttpServletResponse res = (HttpServletResponse) response;
			res.setStatus(403);
		}
	}

}
